/**
 * @desc
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/11/21
 **/
'use strict';
let path  =require('path');
let fse  =require('fs-extra');
var Immutable  =require('immutable');

let widetUtil =require('@qianmi/x-site-common/util/widget-util');
let fileUtil =require('@qianmi/x-site-common/util/file-util');
let templateCompileUtil =require('./template-compile-util');


let widgetCompileUtil = module.exports={};

/**
 * 该方法用到
 * 收集模板依赖的所有组件信息
 * 按模板为维度进度索引,否则搜索开发目录下所有的组件信息
 * @param workBenchPath  req   模板开发所在路径
 * @param templatePathArray  option     只打包这些模板下的内容
 * @param toCompileWidgetPath  option     只打包这些路径过的组件
 */
widgetCompileUtil.collectWidgetInfo = function * ({workBenchPath,templatePathArray,includeDirs,envCode}){
 console.log('templatePathArray',templatePathArray);
 let _ignoreDirs = ignoreDirs.map(item=>path.join(workBenchPath,item,'/').replace(/\\/g,'/'));
 if(templatePathArray && templatePathArray.length >0 ) {
  let allTplBarNs  = [];
  for(let i =0,ilen=templatePathArray.length ; i<ilen; i++) {
   let   templateConfig =  yield templateCompileUtil.generateTplInfo({
    workBenchPath,
    templateConfigPath: templatePathArray[i],
    envCode
   });
   allTplBarNs=allTplBarNs.concat(templateConfig.dependenciesBar);
  }
  console.log("allTplBarNs",allTplBarNs);
 
 
  return getAllWorbenchWidget({
   workBenchPath,
   filtersBarNs:allTplBarNs,
   ignoreDirs:_ignoreDirs,
   includeDirs
  });
 } else {
  return getAllWorbenchWidget({
   workBenchPath,
   ignoreDirs:_ignoreDirs,
   includeDirs
  });
 }
}



// 要忽略掉的目录 ..
let ignoreDirs = [
 path.join('./node_modules'),
 path.join('./settings'),
 path.join('./statics'),
 path.join('./dist'),
 path.join('./.git'),
 path.join('./.idea'),
 path.join('./temp')
];

function getAllWorbenchWidget({workBenchPath,filtersBarNs,ignoreDirs,includeDirs=[]}){
 let compMap={};
 let desiginerN = getWorkBenchName(workBenchPath);
 
 let _includeDirs = includeDirs.map(item=>path.join(item,'/').replace(/\\/g,'/'));
 fileUtil.traceDirTree(workBenchPath,(filePath)=>{
  for(let i =0,ilen=ignoreDirs.length ; i<ilen; i++){
   if(filePath.startsWith(ignoreDirs[i])){
    return ;
   }
  }
  
  //过滤,
  if(_includeDirs && _includeDirs.length > 0){
   let isHit =false;
   for(let i =0,ilen=_includeDirs.length ; i<ilen; i++){
    if(filePath.startsWith(_includeDirs[i])){
     isHit=true;
    }
   }
   
   if(!isHit){
    return ;
   }
  }
  
  //
  if (filePath.endsWith('-p.js')) { //是组件条的情况
   var compFilePath = filePath.replace('-p.js', '').replace('.js', '')
      .replace(new RegExp('.*'+desiginerN), desiginerN);
   
   if(filtersBarNs && filtersBarNs.indexOf(compFilePath)===-1){
    console.log('组件根据模板过滤..不打包组件::',compFilePath);
    return;
   }
   
   var widgetName = widetUtil.extraWidgetNameFromPath(compFilePath);
   //
   if(compMap[compFilePath]){
    
    // console.log(compFilePath,compMap[compFilePath]);
    // throw new Error('组件名重复,请修正!!'+compFilePath);
   } else {
    //其所引用的组件
    let dependenciesBar = searchNameSpaceFromFile({workBenchPath,workDirName:desiginerN,widgetNameSpace:compFilePath}).toJS();
    compMap[compFilePath] = {
     widgetName: widgetName,
     widgetPath: compFilePath,
     widgetNameSpace:compFilePath,
     dependenciesBar
    };
    console.log(compMap[compFilePath]);
   }
  }
 });
 
 console.log('遍历工作目录后, 收集的组件信息::',compMap);
 return compMap;
}


/**
 * 根据指定组件 找到其直接或间接依赖的子组件
 * 如果是项目间的依赖, 那么直接会到 node_modules中去读取 ..
 * @param widgetNameSpace 组件命名空间
 * @param topDir 顶部目录
 **/
function searchNameSpaceFromFile({workBenchPath, workDirName, widgetNameSpace}) {
 let fileContent;
 if (!widgetNameSpace.startsWith(workDirName + '/')) {
  workBenchPath = path.join(workBenchPath, './node_modules/@qianmi',widgetNameSpace.split('/')[0]);
 }
 
 try {
  fileContent = fse.readFileSync(path.join(workBenchPath, '../', widgetNameSpace + "-p.js"));
 } catch (err) {
  console.error(err);
  return Immutable.Set();
 }
 
 //找到defaultProps中对子组件的引用
 var matchResult = fileContent.toString().match(/widgetNameSpace[^,\n]*/g);
 
 if (matchResult && matchResult.length > 0) {
  let result = Immutable.Set();
  matchResult.forEach(item=> {
   let value = item.trim().replace(" ", "", "g").replace("widgetNameSpace", "").replace(":", '').replace(/['|"]/g, "").trim();
   result = result.add(value);
  });
  
  if (result.count() > 0) {
   var result2 = Immutable.Set();
   result.map(subItem=> {
    result2 = result2.union(searchNameSpaceFromFile({workBenchPath, workDirName, widgetNameSpace: subItem}));
   });
   return result.union(result2);
  } else {
   return result;
  }
 } else {
  return Immutable.Set();
 }
 
 
}



function getWorkBenchName(workBenchPath){
 
 let _all  = workBenchPath.split(path.sep);
 let workBenchName = _all[_all.length-1].trim();
 if(!workBenchName){
  workBenchName = _all[_all.length-2].trim();
 }
 return workBenchName;
}